package com.histone.heartbeat.service;

import com.histone.heartbeat.dao.UrlDao;
import com.histone.heartbeat.dao.UserDao;
import com.histone.heartbeat.pojo.UrlEntity;
import com.histone.heartbeat.pojo.UserEntity;
import com.histone.heartbeat.pojo.WxProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class HeartBeatService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private EmailService emailService;

    @Autowired
    private MsgService msgService;

    @Autowired
    private UrlDao urlDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private WxProperties wxProperties;


    @Scheduled(fixedRate = 60000L)
    public void heartBeat(){
        Iterable<UrlEntity> urls = urlDao.findAll();
        urls.forEach(urlEntity -> {
            HttpGet httpGet = new HttpGet(urlEntity.getUrl());
            if (urlEntity.getLevel() == 0){
                //连续失败三次后  剔除该条记录
                log.info("delete url {}", urlEntity);
                urlDao.delete(urlEntity);
                // 发送报警通知
                UserEntity user = userDao.findById(urlEntity.getUserid()).get();
                msgService.sendTemplateMsg(user.getId(), wxProperties.getTemplateid_2(),urlEntity.getUrl(),
                        user.getName(), urlEntity.getName(), urlEntity.getUrl(), "已连续3次检测失败，将不再进行监测。\n如需继续监测，请重新添加网址。");
            } else {
                try {
                    restTemplate.getForEntity(urlEntity.getUrl(), String.class);
                    if(urlEntity.getLevel() == 2 || urlEntity.getLevel() == 1){
                        // 重置可用次数
                        urlEntity.setLevel(3);
                        urlDao.save(urlEntity);
                    }
                } catch (Exception e) {
                    log.error("{} heartbeat error {}, time remain {}", urlEntity, e.getMessage(), urlEntity.getLevel());
                    // 降级
                    urlEntity.setLevel(urlEntity.getLevel() - 1);
                    urlDao.save(urlEntity);
                    // 发送报警通知
                    UserEntity user = userDao.findById(urlEntity.getUserid()).get();
                    // 微信警报
                    msgService.sendTemplateMsg(user.getId(), wxProperties.getTemplateid_1(),urlEntity.getUrl(),
                            user.getName(), urlEntity.getName(), urlEntity.getUrl(), "心跳检测失败，请及时处理");
                    // 邮件警报   邮箱需通过验证
                    if(!StringUtils.isEmpty(user.getEmail()) && "Y".equalsIgnoreCase(user.getEmailVerify())){
                        try {
                            emailService.sendMail(user.getEmail(), "服务器访问故障", urlEntity.getName() + urlEntity.getUrl());
                        } catch (Exception e1) {
                            log.error("send warning email to {} error {}", user.getEmail(), e1.getMessage());
                        }
                    }

                }

            }

        });
    }

}
